package com.maxjay.component.metadata.web.controller;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.applet.resources.MsgAppletViewer;

import com.maxjay.common.util.encode.EncodeUtil;
import com.maxjay.common.util.json.JsonParser;
import com.maxjay.component.metadata.core.command.CreateEntityCommand;
import com.maxjay.component.metadata.core.command.DeleteEntityCommand;
import com.maxjay.component.metadata.core.command.EntityCommand;
import com.maxjay.component.metadata.core.command.UpdateEntityCommand;
import com.maxjay.component.metadata.core.command.processor.EntityCommandProcessor;
import com.maxjay.component.metadata.model.Entity;
import com.maxjay.component.metadata.model.EntityField;
import com.maxjay.component.metadata.model.Record;
import com.maxjay.component.metadata.service.EntityService;
import com.maxjay.system.core.Application;

@SuppressWarnings({"unchecked", "unused"})
public class EntityServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public EntityServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		try {
			Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
			method.setAccessible(true);
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 进入实体新增页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void preCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String entityId = request.getParameter("entityId");
		Entity entity = Application.getEntityContext().getEntityFactory().getEntity(entityId);
		request.setAttribute("entity", entity);
		request.getRequestDispatcher(entity.getEntityConfig().getViewConfig().getCreatePageLocation()).forward(request, response);
	}
	
	/**
	 * 保存实体对象
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		String msg = "保存成功";
		try {
			String entityId = request.getParameter("entityId");
			Entity entity = Application.getEntityContext().getEntityFactory().getEntity(entityId);
			Map<String, Object> entityFieldValMap = parseEntityFieldValMap(entity, request.getParameterMap());
			this.getEntityService().save(entity, new Record(entityFieldValMap));
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			msg = "保存失败，错误信息：" + e.getMessage();
			result.put("success", false);
		}
		result.put("msg", msg);
		response.setCharacterEncoding(EncodeUtil.UTF_8);
		response.getWriter().write(JsonParser.convertObjectToJson(result));
	}
	
	/**
	 * 进入实体对象更新页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void preUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String entityId = request.getParameter("entityId");
		String entityObjId = request.getParameter("entityObjId");
		Entity entity = Application.getEntityContext().getEntityFactory().getEntity(entityId);
		Record dataRecord = this.getEntityService().loadDisplay(entity, entityObjId);
		request.setAttribute("entity", entity);
		request.setAttribute("dataRecord", dataRecord);
		request.getRequestDispatcher(entity.getEntityConfig().getViewConfig().getUpdatePageLocation()).forward(request, response);
	}
	
	/**
	 * 更新实体对象
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		String msg = "更新成功";
		try {
			String entityId = request.getParameter("entityId");
			Entity entity = Application.getEntityContext().getEntityFactory().getEntity(entityId);
			Map<String, Object> entityFieldValMap = parseEntityFieldValMap(entity, request.getParameterMap());
			this.getEntityService().update(entity, new Record(entityFieldValMap));
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			msg = "更新失败，错误信息：" + e.getMessage();
			result.put("success", false);
		}
		result.put("msg", msg);
		response.setCharacterEncoding(EncodeUtil.UTF_8);
		response.getWriter().write(JsonParser.convertObjectToJson(result));
	}
	
	/**
	 * 删除实体对象
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		String msg = "删除成功";
		try {
			String entityId = request.getParameter("entityId");
			String entityObjId = request.getParameter("entityObjId");
			Entity entity = Application.getEntityContext().getEntityFactory().getEntity(entityId);
			this.getEntityService().delete(entity, entityObjId);
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			msg = "删除失败，错误信息：" + e.getMessage();
			result.put("success", false);
		}
		result.put("msg", msg);
		response.setCharacterEncoding(EncodeUtil.UTF_8);
		response.getWriter().write(JsonParser.convertObjectToJson(result));
	}
	
	protected EntityService getEntityService() {
		return Application.getBeanContext().getBean("entityService", EntityService.class);
	}
    
    /**
     * 将request中的参数根据Entity实体对象属性转换为可用的参数
     * 
     * @param entity
     * @param paramArrMap
     * @return
     */
    protected Map<String, Object> parseEntityFieldValMap(Entity entity, Map<String, Object> paramArrMap) {
    	Map<String, Object> fieldValMap = new HashMap<String, Object>();
    	for (EntityField entityField : entity.getEntityFields()) {
    		String paramName = entityField.getName().toUpperCase();
    		String[] paramValArr = (String[])paramArrMap.get(paramName);
    		if (paramValArr == null) {
				continue;
			}
    		String originalVal = paramValArr[0];
//    		String convertVal = EncodeUtil.convertStrEncode(originalVal, EncodeUtil.ISO_8859_1, EncodeUtil.UTF_8);
    		fieldValMap.put(paramName, originalVal);
		}
		return fieldValMap;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}